import * as Api from '@/api/page'
// 后端api地址
const baseUrl = config.get('apiUrl')
const httpTokenRequest = (opts, data) => {
	let token = uni.getStorageSync('token')
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: opts.data,
		method: opts.method,
		header: opts.method == 'GET' ? {
			'X-ACCESS-TOKEN': token,
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'X-ACCESS-TOKEN': token,
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/json; charset=UTF-8'
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(  
			(res) => {
				if(res[0] && res[0].errMsg){
					uni.showToast({
						title: '网络异常！',
						icon: 'none'
					});
				}else{
					if(res[1].data.code == 401){
						//401代表token过期，此时会调用获取token的接口
						let userIfo = uni.getStorage('userifo');
						var params = {
						    username: userIfo.username,
						    password: userIfo.password 
						}
						Api.loginAcmont(params).then(res=> {
						    if (res.code == 200) {
						        //本地存储能力 120107199001244532  13087946216 
						        uni.setStorageSync('admin_token', res.token);
							    Api.getUserInfo().then(response => {
									if(response.code==200){
										uni.setStorage({
											key: 'userifo',
											data: JSON.stringify(response.data)
										})
										httpTokenRequest(opts, data).then(res=>{
											resolve(res)
										})
									}
							    })
						    } 
						})
						getToken().then(res =>{
							//token获取成功后，httpTokenRequest自己调用自己，注意：由于上一个httpTokenRequest里的promise没有执行完就调用自己又开启一个promise，所以
							//then返回的res是调用自己后reslove（res[1]）的结果。reslove(res),才是最后返回的数据
							httpTokenRequest(opts, data).then(res=>{
								resolve(res)
							})
						})
					}else{
						resolve(res[1])
					}
					
				}
			}
		)
		.catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};
